<template>
  <div class="app-container">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select filterable placeholder="请选择门店" v-model="formInline.store_id" style="width:300px">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-date-picker style="width:120px" value-format="yyyy-MM" v-model="pickerDate" :editable="false" :clearable="false" type="month" size="small"
          :picker-options="pickerOptions" placeholder="选择月">
        </el-date-picker>
        <el-form-item>
          <el-select @change="typeChange" filterable v-model="type" style="width:130px">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 营收列表 -->
      <transition name="el-fade-in">
        <el-table v-show="formInline.type==1" highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small" show-summary
          :summary-method="getSummaries">
          <el-table-column align="center" label='门店信息'>
            <el-table-column align="center" label="序号" width="80">
              <template slot-scope="scope">
                <div class="indexColor">{{scope.$index+1}}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label='门店名称' prop="name" sortable></el-table-column>
          </el-table-column>
          <el-table-column align="center" label="营收类指标">
            <el-table-column align="center" label='营收指标' sortable prop="income_money">
              <template slot-scope="scope">
                <div class="confirmDiv">
                  <el-input style="width:180px;height:40px" :maxlength="inputLength" v-model="scope.row.income_money" placeholder="请输入金额"
                    v-if="!scope.row.isSave"></el-input>
                  <div class="indexDiv" v-else>{{scope.row.income_money}}</div>
                  <img @click="getHistory(scope.row.id,1)" class="report-form" src="../../assets/images/report-form.png" alt="">
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label='消费类指标'>
            <el-table-column align="center" label="摊位机指标" sortable prop="booth_machine_money">
              <template slot-scope="scope">
                <div class="confirmDiv">
                  <el-input style="width:180px" :maxlength="inputLength" v-model="scope.row.booth_machine_money" placeholder="请输入金额" v-if="!scope.row.isSave">
                  </el-input>
                  <div class="indexDiv" v-else>{{scope.row.booth_machine_money}}</div>
                  <img @click="getHistory(scope.row.id,2)" class="report-form" src="../../assets/images/report-form.png" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label='礼品机指标' sortable prop="gift_machine_money">
              <template slot-scope="scope">
                <div class="confirmDiv">
                  <el-input style="width:180px" :maxlength="inputLength" v-model="scope.row.gift_machine_money" placeholder="请输入金额" v-if="!scope.row.isSave">
                  </el-input>
                  <div class="indexDiv" v-else>{{scope.row.gift_machine_money}}</div>
                  <img @click="getHistory(scope.row.id,3)" class="report-form" src="../../assets/images/report-form.png" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label='彩票机指标' sortable prop="lottery_machine_money">
              <template slot-scope="scope">
                <div class="confirmDiv">
                  <el-input style="width:180px" :maxlength="inputLength" v-model="scope.row.lottery_machine_money" placeholder="请输入金额" v-if="!scope.row.isSave">
                  </el-input>
                  <div class="indexDiv" v-else>{{scope.row.lottery_machine_money}}</div>
                  <img @click="getHistory(scope.row.id,4)" class="report-form" src="../../assets/images/report-form.png" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label='门禁项目指标' sortable prop="pass_business_money">
              <template slot-scope="scope">
                <div class="confirmDiv">
                  <el-input style="width:180px" :maxlength="inputLength" v-model="scope.row.pass_business_money" placeholder="请输入金额" v-if="!scope.row.isSave">
                  </el-input>
                  <div class="indexDiv" v-else>{{scope.row.pass_business_money}}</div>
                  <img @click="getHistory(scope.row.id,5)" class="report-form" src="../../assets/images/report-form.png">
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <!-- 列表的操作按钮 -->
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isSave==0" @click="saveClick(1,scope.row,scope.$index)" type="primary" size="small">保存</el-button>
              <el-button v-else @click="saveClick(2,scope.row,scope.$index)" :disabled="scope.row.confirm==1||isDisabled" type="primary" size="small">修改
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.confirm==1">已确认</span>
              <span v-else style="color:red">未确认</span>
            </template>
          </el-table-column>
        </el-table>
      </transition>
      <!-- 订货列表 -->
      <transition name="el-fade-in">
        <el-table v-show="formInline.type==2" highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small">
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              <div class="indexColor">{{scope.$index+1}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label='门店名称' prop="name" sortable></el-table-column>
          <el-table-column align="center" label='订货指标' sortable prop="money">
            <template slot-scope="scope">
              <div class="confirmDiv">
                <el-input style="width:180px;height:40px" v-model="scope.row.money" placeholder="请输入金额" v-if="!scope.row.isSave"></el-input>
                <div class="indexDiv" v-else>{{scope.row.money}}</div>
              </div>
            </template>
          </el-table-column>
          <!-- 列表的操作按钮 -->
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isSave==0" @click="saveClick(3,scope.row,scope.$index)" type="primary" size="small">保存</el-button>
              <el-button v-else @click="saveClick(2,scope.row,scope.$index)" :disabled="isOrderDisabled" type="primary" size="small">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>
      <!-- 弹框 -->
      <el-dialog :close-on-click-modal="false" width="800px" title="营收指标历史趋势图" center :visible.sync="historyDialog">
        <line-chart :chart-data="lineChartData" :legendData="legendData" :selectedData="selectedData" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getList, getStoreList, goalUpdate, orderUpdate, historySelect } from '@/api/operation/indexEntry.js';
import { money, integer0to9999999, null0to } from '@/utils/validate';
import { pickerOptionsMonth } from '@/utils';
import LineChart from '../dashboard/components/LineChart';
export default {
  data() {
    return {
      list: [],
      oldData: null,
      oldOrderData: null,
      listLoading: false,
      isDisabled: false,
      isOrderDisabled: false,
      historyDialog: false,
      inputLength: 7,
      type: '1',
      storeList: [{ id: 0, name: '全部门店' }],
      typeList: [
        { id: '1', name: '总部考核指标' },
        { id: '2', name: '总部订货指标' }
      ],
      formInline: {
        store_id: 0,
        datetime: '',
        type: '1',
        look_del: '0'
      },
      saveForm: {
        revenue: '',
        booth: '',
        gift: '',
        lottery: '',
        access: ''
      },
      lineChartData: {
        dimensions: ['product', '考核值', '实际完成值'],
        source: []
      },
      legendData: ['考核值', '实际完成值'],
      selectedData: {
        考核值: true,
        实际完成值: true
      },
      dialogTitle: '',
      dialogFormVisible: false,
      pickerDate: new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth() + 1)).toISOString().slice(0, 7),
      pickerOptions: pickerOptionsMonth(3)
    };
  },
  created() {
    this.getStore();
    //this.fetchData();
  },
  methods: {
    saveClick(i, row, index) {
      if (i == 1) {
        // console.log(row,index)
        if (
          (row.income_money && !integer0to9999999(row.income_money)) ||
          (row.booth_machine_money && !integer0to9999999(row.booth_machine_money)) ||
          (row.gift_machine_money && !integer0to9999999(row.gift_machine_money)) ||
          (row.lottery_machine_money && !integer0to9999999(row.lottery_machine_money)) ||
          (row.pass_business_money && !integer0to9999999(row.pass_business_money))
        ) {
          this.$message.error('指标范围为0-9999999的整数，请重新设置');
          return;
        }
        let data = {};
        data.store_id = row.id;
        data.datetime = this.formInline.datetime;
        data.income_money = row.income_money;
        data.income_money_status = row.income_money_status == 1 ? '1' : row.income_money === '' || !row.income_money ? '0' : '1';
        data.booth_machine_money = row.booth_machine_money;
        data.booth_machine_money_status = row.booth_machine_money_status == 1 ? '1' : row.booth_machine_money === '' || !row.booth_machine_money ? '0' : '1';
        data.gift_machine_money = row.gift_machine_money;
        data.gift_machine_money_status = row.gift_machine_money_status == 1 ? '1' : row.gift_machine_money === '' || !row.gift_machine_money ? '0' : '1';
        data.lottery_machine_money = row.lottery_machine_money;
        data.lottery_machine_money_status =
          row.lottery_machine_money_status == 1 ? '1' : row.lottery_machine_money === '' || !row.lottery_machine_money ? '0' : '1';
        data.pass_business_money = row.pass_business_money;
        data.pass_business_money_status = row.pass_business_money_status == 1 ? '1' : row.pass_business_money === '' || !row.pass_business_money ? '0' : '1';
        row.isSave = 1;
        if (
          data.income_money == this.oldData[index].income_money &&
          data.booth_machine_money == this.oldData[index].booth_machine_money &&
          data.gift_machine_money == this.oldData[index].gift_machine_money &&
          data.lottery_machine_money == this.oldData[index].lottery_machine_money &&
          data.pass_business_money == this.oldData[index].pass_business_money
        ) {
          return;
        }
        goalUpdate(data).then(res => {
          //console.log(res)
          this.$message({ type: res.code == 1 ? 'success' : 'error', message: res.message });
          if (res.code == 1) {
            this.oldData[index].income_money = data.income_money;
            this.oldData[index].booth_machine_money = data.booth_machine_money;
            this.oldData[index].gift_machine_money = data.gift_machine_money;
            this.oldData[index].lottery_machine_money = data.lottery_machine_money;
            this.oldData[index].pass_business_money = data.pass_business_money;
            this.oldData[index].income_money_status = data.income_money_status;
            this.oldData[index].gift_machine_money_status = data.gift_machine_money_status;
            this.oldData[index].lottery_machine_money_status = data.lottery_machine_money_status;
            this.oldData[index].pass_business_money_status = data.pass_business_money_status;
            this.oldData[index].booth_machine_money_status = data.booth_machine_money_status;
          }
        });
      } else if (i == 3) {
        if (!null0to(row.money) || row.money == '') {
          row.isSave = 1;
          row.money = this.oldOrderData[index].money;
          return;
        }
        if (this.oldOrderData[index].money == row.money) {
          row.isSave = 1;
          return;
        }
        orderUpdate({ store_id: row.store_id, money: row.money, datetime: this.formInline.datetime }).then(res => {
          this.$message({ type: res.code == 1 ? 'success' : 'error', message: res.message });
          if (res.code == 1) {
            this.oldOrderData[index].money = row.money;
            row.isSave = 1;
          }
        });
      } else {
        row.isSave = 0;
        // this.oldData=JSON.parse(JSON.stringify(row));
      }
    },
    onSubmit() {
      this.fetchData();
    },
    changeNum(row, key) {
      if ((row[key] >= 1 && row[key] <= 9999999 && money(row[key])) || !row[key]) row.isMoney = true;
      else row.isMoney = -1;
      row[key] *= 1;
      if (!row[key]) row[key] = '';
    },
    //合计
    getSummaries(param) {
      //console.log(param);
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1) {
          sums[index] = '-';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        //console.log(values)
        if (index > 0 && column.label != '门店名称') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = (sums[index] * 1).toFixed(2) * 1;
          } else {
            sums[index] = '-';
          }
        }
      });
      return sums;
    },
    // 门店列表获取
    getStore() {
      getStoreList({ look_del: this.formInline.look_del, category_id: 402 }).then(response => {
        this.storeList = response;
        //this.formInline.store_id = response[0].id;
        let data = response.filter(res => res.id == this.$store.getters.optionId);
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        }
        this.fetchData();
      });
    },

    searchClick() {
      this.fetchData();
    },
    typeChange(type) {
      if (type == 1) {
        this.pickerDate = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth() + 1)).toISOString().slice(0, 7);
        this.pickerOptions = pickerOptionsMonth(3);
      } else {
        this.pickerDate = new Date(Date.UTC(new Date().getFullYear(), new Date().getMonth() + 2)).toISOString().slice(0, 7);
        this.pickerOptions = pickerOptionsMonth(2);
      }
    },
    async fetchData() {
      this.listLoading = true;
      this.formInline.type = this.type;
      this.formInline.datetime = this.pickerDate;
      let checkMonth = this.pickerDate.replace(/\b(0+)/gi, '');
      let mon = new Date(checkMonth) / 1000;
      let date = new Date();
      let cunMon = new Date(date.getFullYear() + '-' + (date.getMonth() + 1)) / 1000;
      let orderMon = new Date(date.getFullYear() + '-' + (date.getMonth() + 3)) / 1000;
      if (mon < orderMon) {
        this.isOrderDisabled = true;
      } else {
        this.isOrderDisabled = false;
      }
      if (cunMon > mon) {
        this.isDisabled = true;
      } else {
        this.isDisabled = false;
      }
      try {
        // this.formInline.datetime=this.pickerDate.split(".")[0]+"-"+parseInt(this.pickerDate.split(".")[1]);
        let res = await getList({ store_id: this.formInline.store_id, datetime: this.formInline.datetime, type: this.formInline.type });
        if (this.formInline.type == 1) {
          res.forEach((val, i) => {
            val.isSave = 1;
            val.income_money = val.income_money_status == 0 ? '' : val.income_money / 100;
            val.booth_machine_money = val.booth_machine_money_status == 0 ? '' : val.booth_machine_money / 100;
            val.gift_machine_money = val.gift_machine_money_status == 0 ? '' : val.gift_machine_money / 100;
            val.lottery_machine_money = val.lottery_machine_money_status == 0 ? '' : val.lottery_machine_money / 100;
            val.pass_business_money = val.pass_business_money_status == 0 ? '' : val.pass_business_money / 100;
          });
          this.oldData = JSON.parse(JSON.stringify(res));
        } else {
          res.forEach(val => {
            val.money = val.money == -1 ? '' : val.money;
            val.isSave = 1;
          });
          this.oldOrderData = JSON.parse(JSON.stringify(res));
        }
        this.list = res;
        //console.log(this.list)
        this.listLoading = false;
      } catch (err) {
        this.$message.error(err);
        this.listLoading = false;
      }
    },
    //弹窗
    getHistory(store_id, type) {
      this.listLoading = true;
      this.historyDialog = true;
      historySelect({ store_id, type }).then(res => {
        //console.log(Array.isArray(res));
        this.lineChartData.source = [];
        if (Array.isArray(res)) {
          for (let val of res) {
            this.lineChartData.source.unshift({ product: val.datetime, 考核值: val.goal_money, 实际完成值: val.actual_money });
          }
        }

        this.listLoading = false;
      });
    }
  },
  components: { LineChart }
};
</script>

<style scoped>
div.confirmDiv {
  position: relative;
  height: 40px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
div.indexDiv {
  display: inline-block;
  font-size: 12px;
  width: 180px;
  height: 32px;
  text-align: center;
  line-height: 30px;
}
img.report-form {
  width: 20px;
  height: 20px;

  cursor: pointer;
}
</style>
